﻿using System.Diagnostics;
using System.Management;

namespace DotNetServiceLib
{
    public class ProcessUtil
    {
        /// <summary>
        /// If a process was not succesfully ended or if it still running, we must prevent our service to launch it again
        /// since it could substancially reduce the machine's memory and eventually tear it down. It was after tearing down a few
        /// times a server that I noticed how critical this issue was :)
        /// </summary>
        /// <param name="name">Process's name</param>
        /// <returns></returns>
        public static bool IsProcessOpen(string name)
        {
            bool isOpen = false;
            ManagementClass MgmtClass = new ManagementClass("Win32_Process");
            foreach (ManagementObject mo in MgmtClass.GetInstances())
            {
                if (mo["Name"].ToString() == name)
                {
                    isOpen = true;
                    break;
                }
            }
            return isOpen;
        }
    }
}
